package written;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 现在有两种线程，氧 oxygen 和氢 hydrogen，你的目标是组织这两种线程来产生水分子。
 * <p>
 * 存在一个屏障（barrier）使得每个线程必须等候直到一个完整水分子能够被产生出来。
 * <p>
 * 氢和氧线程会被分别给予 releaseHydrogen 和 releaseOxygen 方法来允许它们突破屏障。
 * <p>
 * 这些线程应该三三成组突破屏障并能立即组合产生一个水分子。
 * <p>
 * 你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。
 * <p>
 * 换句话说:
 * <p>
 * 如果一个氧线程到达屏障时没有氢线程到达，它必须等候直到两个氢线程到达。
 * 如果一个氢线程到达屏障时没有其它线程到达，它必须等候直到一个氧线程和另一个氢线程到达。
 * <p>
 * 输入: "HOH"
 * 输出: "HHO"
 * 解释: "HOH" 和 "OHH" 依然都是有效解。
 *
 * @author TANGYE
 * @date 2021-01-10 21:58
 **/
public class H2OCreate {

    private static class H2O {

        private char[] genArr;
        private volatile boolean hSignal = false;
        private volatile boolean oSignal = false;
        private StringBuilder hGen = new StringBuilder();
        private StringBuilder oGen = new StringBuilder();
        private int hNum = 0;
        private int oNum = 0;

        public H2O(char[] genArr) {
            this.genArr = genArr;
        }

        public void releaseHydrogen() {
            hSignal = true;
            while (!hSignal || !oSignal) {

            }
            System.out.print(hGen.toString());
            hGen = new StringBuilder();
            hSignal = false;
            while (oSignal) {

            }
            hNum = 0;
        }

        public void releaseOxygen() {
            oSignal = true;
            while (!hSignal || !oSignal) {

            }
            System.out.print(oGen.toString());
            oGen = new StringBuilder();
            oSignal = false;
            while (hSignal) {

            }
            oNum = 0;
        }

        public void createHgen() {
            int hIndex = 0;
            while (hIndex < genArr.length) {
                if (genArr[hIndex++] == 'H') {
                    hNum++;
                    hGen.append('H');
                    if (hNum == 2) {
                        releaseHydrogen();
                    }
                }
            }
        }

        public void createOgen() {
            int oIndex = 0;
            while (oIndex < genArr.length) {
                if (genArr[oIndex++] == 'O') {
                    oNum++;
                    oGen.append('O');
                    if (oNum == 1) {
                        releaseOxygen();
                    }
                }
            }

        }

    }

    public static void main(String[] args) {
        H2O h2O = new H2O("HOHHHOOOHHOHHHH".toCharArray());
        Thread tO = new Thread(() -> h2O.createOgen());
        Thread tH = new Thread(() -> h2O.createHgen());
        tO.start();
        tH.start();

    }
}
